<?php
/**
 * CustomerRepo.php
 *
 * @copyright  2023 beikeshop.com - All Rights Reserved
 * @link       https://beikeshop.com
 * @author     TL <mengwb@guangda.work>
 * @created    2023-04-19 17:45:41
 * @modified   2023-04-19 17:45:41
 */

namespace Beike\Seller\Repositories;

use Beike\Seller\Models\Seller;
use Beike\Seller\Models\SellerUser;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Hash;

class SellerRepo
{
    private static $mapIdToStoreName = null;

    /**
     * 创建一个seller_user记录
     * @param $data
     * @return Seller
     * @throws \Throwable
     */
    public static function create($data): Seller
    {
        $seller = new Seller([
            'email'           => $data['email'],
            'telephone'       => $data['telephone'] ?? '',
            'company'         => $data['company'] ?? '',
            'description'     => $data['description'] ?? '',
            'seller_group_id' => $data['seller_group_id'],
            'store_name'      => $data['store_name'],
            'product_approve' => $data['product_approve'],
            'type'            => $data['type'],
            'id_card'         => $data['id_card'],
            'id_number'       => $data['id_number'],
            'status'          => $data['status'],
            'approved'        => $data['approved'] ?? 1,
        ]);
        $seller->saveOrFail();

        $sellerUserData = [
            'seller_user_group_id' => $data['seller_user_group_id'],
            'email'                => $data['email'] ?? '',
            'password'             => Hash::make($data['password'] ?? ''),
            'locale'               => $data['locale'],
            'is_root'              => true,
            'status'               => 1,
        ];
        if ($data['email'] ?? '') {
            $sellerUserData['name'] = substr($data['email'], 0, strrpos($data['email'], '@'));
        }
        $seller->users()->save(new SellerUser($sellerUserData));

        return $seller;
    }

    /**
     * @param $seller
     * @param $data
     * @return bool|int
     */
    public static function update($seller, $data)
    {
        if (! $seller instanceof Seller) {
            $seller = Seller::query()->findOrFail($seller);
        }

        return $seller->update($data);
    }

    /**
     * @param $value
     * @param $exceptIds
     * @return void
     */
    public static function updateFieldProductApprove($value, $exceptIds)
    {
        Seller::query()->whereNotIn('id', $exceptIds)->update(['product_approve' => $value]);
        Seller::query()->whereIn('id', $exceptIds)->update(['product_approve' => !$value]);
    }

    public static function getSellersByProductApprove($productApprove)
    {
        return Seller::query()->where('product_approve', $productApprove)->get();
    }

    /**
     * @param $email
     * @return Builder|Model|object|null
     */
    public static function findByEmail($email)
    {
        return Seller::query()->where('email', $email)->first();
    }

    /**
     * @param $id
     * @return Builder|Builder[]|Collection|Model|null
     */
    public static function find($id)
    {
        return Seller::query()->find($id);
    }

    /**
     * @param $id
     * @return void
     * @throws \Exception
     */
    public static function delete($id): void
    {
        Seller::query()->find($id)->delete();
    }

    /**
     * @param $data
     * @return LengthAwarePaginator
     */
    public static function list($data): LengthAwarePaginator
    {
        $builder = self::getListBuilder($data);

        return $builder->paginate(perPage())->withQueryString();
    }

    /**
     * @return array|null
     */
    public static function mapIdToStoreName()
    {
        if (self::$mapIdToStoreName === null) {
            $sellers                = self::getListBuilder()->select(['id', 'store_name'])->get()->toArray();
            self::$mapIdToStoreName = array_column($sellers, 'store_name', 'id');
        }

        return self::$mapIdToStoreName;
    }

    /**
     * 获取筛选对象
     *
     * @param array $filters
     * @return Builder
     */
    public static function getListBuilder(array $filters = []): Builder
    {
        $builder = Seller::query();

        if (isset($filters['email'])) {
            $builder->where('sellers.email', 'like', "%{$filters['email']}%");

            // 验证邮箱是否填写正确
            if (filter_var($filters['email'], FILTER_VALIDATE_EMAIL)) {
                $builder->orWhereHas('users', function ($query) use ($filters) {
                    $query->where('email', 'like', "%{$filters['email']}%");
                });
            }
        }

        if (isset($filters['status'])) {
            $builder->where('sellers.status', (int) $filters['status']);
        }
        if (isset($filters['store_name'])) {
            $builder->where('sellers.store_name', $filters['store_name']);
        }
        if (isset($filters['like_store_name'])) {
            $builder->where('sellers.store_name', 'like', '%' . $filters['like_store_name'] . '%');
        }
        if (isset($filters['seller_group_id'])) {
            $builder->where('sellers.seller_group_id', $filters['seller_group_id']);
        }

        $sellerIds = $data['seller_ids'] ?? [];
        if ($sellerIds) {
            $builder->whereIn('sellers.id', $sellerIds);
        }

        $start = $filters['start'] ?? null;
        if ($start) {
            $builder->where('sellers.created_at', '>', $start);
        }

        $end = $filters['end'] ?? null;
        if ($end) {
            $builder->where('sellers.created_at', '<', $end);
        }

        $builder->orderByDesc('sellers.created_at');

        return $builder;
    }

    /**
     * @param $ids
     * @return Collection|array
     */
    public static function getSellersByIds($ids): Collection|array
    {
        if (! $ids) {
            return new Collection();
        }
        $sellers  = static::getListBuilder(['seller_ids' => $ids])->get();

        return $sellers;
    }

    /**
     * @param $id
     * @param $status
     * @return bool|int
     */
    public static function approve($id, $status)
    {
        return self::find($id)->update(['approved' => 1, 'status' => $status]);
    }


    public static function autocomplete($name)
    {
        $filter = [];
        if ($name) {
            $filter['like_store_name'] = $name;
        }
        $builder = self::getListBuilder($filter)->select(['store_name', 'id']);

        return $builder->limit(10)->get();
    }
}
